<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JWT认证调试页面</title>
    <link rel="stylesheet" href="assets/css/font-awesome.css">
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            margin: 0;
            padding: 20px;
            background: #f8f9fa;
            line-height: 1.6;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 20px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem;
            text-align: center;
        }

        .header h1 {
            margin: 0;
            font-size: 2rem;
        }

        .content {
            padding: 2rem;
        }

        .section {
            margin-bottom: 2rem;
            padding: 1.5rem;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }

        .section h3 {
            margin-top: 0;
            color: #333;
        }

        .btn {
            display: inline-block;
            padding: 0.75rem 1.5rem;
            margin: 0.5rem;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            text-decoration: none;
            font-size: 0.9rem;
            transition: all 0.3s ease;
        }

        .btn:hover {
            background: #5a6fd8;
            transform: translateY(-2px);
        }

        .btn-success {
            background: #28a745;
        }

        .btn-success:hover {
            background: #218838;
        }

        .btn-danger {
            background: #dc3545;
        }

        .btn-danger:hover {
            background: #c82333;
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 1rem;
            margin: 1rem 0;
        }

        .info-card {
            background: white;
            padding: 1rem;
            border-radius: 8px;
            border: 1px solid #e9ecef;
        }

        .info-label {
            font-weight: 600;
            color: #6c757d;
            font-size: 0.9rem;
            margin-bottom: 0.5rem;
        }

        .info-value {
            font-family: monospace;
            background: #f8f9fa;
            padding: 0.5rem;
            border-radius: 4px;
            word-break: break-all;
            font-size: 0.85rem;
        }

        .status-ok {
            color: #28a745;
        }

        .status-error {
            color: #dc3545;
        }

        .log-area {
            background: #212529;
            color: #f8f9fa;
            padding: 1rem;
            border-radius: 8px;
            font-family: monospace;
            font-size: 0.85rem;
            height: 300px;
            overflow-y: auto;
            margin: 1rem 0;
        }

        .alert {
            padding: 1rem;
            border-radius: 6px;
            margin: 1rem 0;
        }

        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .alert-danger {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .alert-warning {
            background: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-bug"></i> JWT认证调试页面</h1>
            <p>诊断和修复前后端JWT认证问题</p>
        </div>

        <div class="content">
            <div class="section">
                <h3><i class="fas fa-info-circle"></i> 当前认证状态</h3>
                <div class="info-grid">
                    <div class="info-card">
                        <div class="info-label">登录状态</div>
                        <div class="info-value" id="loginStatus">检查中...</div>
                    </div>
                    <div class="info-card">
                        <div class="info-label">Token存在</div>
                        <div class="info-value" id="tokenExists">检查中...</div>
                    </div>
                    <div class="info-card">
                        <div class="info-label">Token长度</div>
                        <div class="info-value" id="tokenLength">检查中...</div>
                    </div>
                    <div class="info-card">
                        <div class="info-label">用户信息</div>
                        <div class="info-value" id="userInfo">检查中...</div>
                    </div>
                </div>
            </div>

            <div class="section">
                <h3><i class="fas fa-cog"></i> 快速操作</h3>
                <button class="btn" onclick="testLogin()">
                    <i class="fas fa-sign-in-alt"></i> 测试登录
                </button>
                <button class="btn" onclick="testAPI()">
                    <i class="fas fa-server"></i> 测试API调用
                </button>
                <button class="btn btn-success" onclick="refreshStatus()">
                    <i class="fas fa-sync-alt"></i> 刷新状态
                </button>
                <button class="btn btn-danger" onclick="clearAuth()">
                    <i class="fas fa-trash"></i> 清除认证信息
                </button>
            </div>

            <div class="section">
                <h3><i class="fas fa-terminal"></i> 调试日志</h3>
                <div class="log-area" id="logArea"></div>
                <button class="btn" onclick="clearLogs()">
                    <i class="fas fa-eraser"></i> 清除日志
                </button>
            </div>

            <div class="section">
                <h3><i class="fas fa-tools"></i> 常见问题解决方案</h3>
                <div class="alert alert-warning">
                    <strong>问题：</strong>我的文章页面显示"系统内部错误"
                    <br><strong>解决：</strong>
                    1. 检查上方的Token状态
                    2. 如果Token不存在，点击"测试登录"重新登录
                    3. 如果Token存在但无效，点击"清除认证信息"后重新登录
                </div>
            </div>
        </div>
    </div>

    <script>
        const API_BASE = 'http://localhost:8080/api';
        
        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            log('页面初始化');
            refreshStatus();
        });

        // 刷新状态
        function refreshStatus() {
            log('🔍 检查认证状态...');
            
            const token = localStorage.getItem('token');
            const user = localStorage.getItem('user');
            const userRoles = localStorage.getItem('userRoles');
            
            // 更新界面显示
            document.getElementById('tokenExists').innerHTML = token ? 
                '<span class="status-ok">✓ 存在</span>' : 
                '<span class="status-error">✗ 不存在</span>';
                
            document.getElementById('tokenLength').textContent = token ? token.length + ' 字符' : '0';
            
            if (user) {
                try {
                    const userObj = JSON.parse(user);
                    document.getElementById('userInfo').textContent = `${userObj.username} (${userObj.role})`;
                    document.getElementById('loginStatus').innerHTML = '<span class="status-ok">✓ 已登录</span>';
                } catch (e) {
                    document.getElementById('userInfo').textContent = '解析失败';
                    document.getElementById('loginStatus').innerHTML = '<span class="status-error">✗ 用户信息无效</span>';
                }
            } else {
                document.getElementById('userInfo').textContent = '无';
                document.getElementById('loginStatus').innerHTML = '<span class="status-error">✗ 未登录</span>';
            }

            log(`Token: ${token ? '存在(' + token.length + '字符)' : '不存在'}`);
            log(`用户: ${user || '无'}`);
            log(`角色: ${userRoles || '无'}`);
        }

        // 测试登录
        async function testLogin() {
            log('🚀 测试登录...');
            
            try {
                const response = await fetch(`${API_BASE}/user/login`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username: 'admin',
                        password: '123456'
                    })
                });

                const result = await response.json();
                log(`登录响应: ${JSON.stringify(result, null, 2)}`);

                if (result.code === 0) {
                    // 保存认证信息
                    localStorage.setItem('user', JSON.stringify(result.data.user));
                    localStorage.setItem('token', result.data.token);
                    localStorage.setItem('refreshToken', result.data.refreshToken);
                    localStorage.setItem('userRoles', JSON.stringify(result.data.roles));
                    localStorage.setItem('userPermissions', JSON.stringify(result.data.permissions));
                    
                    log('✅ 登录成功！认证信息已保存');
                    refreshStatus();
                } else {
                    log(`❌ 登录失败: ${result.message}`);
                }
            } catch (error) {
                log(`❌ 登录请求失败: ${error.message}`);
            }
        }

        // 测试API调用
        async function testAPI() {
            log('🚀 测试API调用...');
            
            const token = localStorage.getItem('token');
            if (!token) {
                log('❌ 没有Token，请先登录');
                return;
            }

            try {
                log('发送请求到: /api/user/articles/stats');
                log(`Authorization头: Bearer ${token.substring(0, 20)}...`);
                
                const response = await fetch(`${API_BASE}/user/articles/stats`, {
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });

                log(`响应状态: ${response.status} ${response.statusText}`);
                
                const result = await response.json();
                log(`响应内容: ${JSON.stringify(result, null, 2)}`);

                if (response.ok && result.code === 0) {
                    log('✅ API调用成功！');
                } else {
                    log(`❌ API调用失败: ${result.message || '未知错误'}`);
                }
            } catch (error) {
                log(`❌ API请求失败: ${error.message}`);
            }
        }

        // 清除认证信息
        function clearAuth() {
            localStorage.removeItem('user');
            localStorage.removeItem('token');
            localStorage.removeItem('refreshToken');
            localStorage.removeItem('userRoles');
            localStorage.removeItem('userPermissions');
            
            log('🧹 认证信息已清除');
            refreshStatus();
        }

        // 记录日志
        function log(message) {
            const logArea = document.getElementById('logArea');
            const timestamp = new Date().toLocaleTimeString();
            logArea.innerHTML += `[${timestamp}] ${message}\n`;
            logArea.scrollTop = logArea.scrollHeight;
        }

        // 清除日志
        function clearLogs() {
            document.getElementById('logArea').innerHTML = '';
            log('日志已清除');
        }
    </script>
</body>
</html>
